package logic

import (
	"context"
	"fmt"
	"user3/model/mysql"
	"user3/model/redis"
	"user3/pkg"

	"user3/userrpc/internal/svc"
	"user3/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("captcharegister" + in.Account)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("图形验证码错误,请重新尝试")
	}
	cmd := redis.Client.Get("sendsmsregister" + in.Account)
	if cmd.Val() != in.Send {
		return nil, fmt.Errorf("短信验证码错误，请重新尝试")
	}
	var finduser mysql.User
	mysql.DB.Where("tel=?", in.Account).Find(&finduser)
	if finduser.ID != 0 {
		return nil, fmt.Errorf("该用户已被注册，请重新输入")
	}
	var user = mysql.User{
		Tel:      in.Account,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Create(&user)

	redis.Client.Del("captcharegister" + in.Account)
	redis.Client.Del("sendsmsregister" + in.Account)

	return &userrpc.RegisterResponse{Id: int64(user.ID)}, nil
}
